<?php
/**
 * 配置相关方法.
 *
 * Author:李强 EdwinLee
 * Company:上海煦鸣网络科技有限公司
 * Time: 2018-04-19 13:28
 */

namespace App\Traits;

use Illuminate\Support\Facades\Cache;
use Mockery\Matcher\Closure;

trait ConfigCache
{
    /**
     * 保存数据到缓存
     *
     * @param array $wheres
     * @param string $orderBys
     * @return mixed
     */
    public static function cacheData($wheres = [], $orderBys = '')
    {
        self::when(!empty($wheres), function ($query) use ($wheres) {
            foreach ($wheres as $method => $where) {
                foreach ($where as $item) {
                    if ($item instanceof Closure) {
                        $query->{$method}($item);
                    } elseif (is_array($item)) {
                        $query->{$method}(...$item);
                    }
                }
            }
        })->when(is_array($orderBys) && !empty($orderBys), function ($query) use ($orderBys) {
            foreach ($orderBys as $k => $order) {
                $query->orderBy($k, $order);
            }
        })->chunk(100, function ($attrs) use (&$data_list) {
            foreach ($attrs as $attr) {
                $data_list[$attr->{self::$key}] = $attr;
            }
        });
        Cache::forever(self::$cache_key, serialize($data_list));
        return $data_list;
    }

    /**
     * 获取缓存数据
     *
     * @param array $where
     * @param string $orderBys
     * @param int $reload
     * @return mixed
     */
    public static function getCache($where = [], $orderBys = '', $reload = 0)
    {
        $attrs = null;
        if ($reload == 0) {
            $attrs = Cache::get(self::$cache_key);
        }
        if (is_null($attrs)) {
            return self::cacheData($where, $orderBys);
        } else {
            return unserialize($attrs);
        }
    }

    /**
     * 按某项分组获取缓存数据
     *
     * @param string $group_key
     * @param array $where
     * @param string $orderBys
     * @param int $reload
     * @return array|mixed
     */
    public static function getGroupCache($group_key = '',$where = [], $orderBys = '', $reload = 0)
    {
        $attributes = [];
        $attrs = null;
        $cache_key = self::$cache_key . "." . $group_key;
        if ($reload == 0) {
            $attrs = Cache::get($cache_key);
        }
        if (is_null($attrs)) {
            //获取数据
            $datas = self::getCache($where, $orderBys, 1);
            if (is_null($datas)) {
                return [];
            } else {
                foreach ($datas as $data) {
                    $attributes[$data[$group_key]][$data[self::$key]] = $data;
                }
                Cache::forever($cache_key, serialize($attributes));
                return $attributes;
            }
        } else {
            return unserialize($attrs);
        }
    }
}